<template>
  <!-- 添加或修改项目基础信息管理对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body v-dialogDrag width="90%">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true"
             label-width="98px">
      <el-form-item label="工程名称" prop="gongchengName">
        <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品编码" prop="goodsCode">
        <el-input v-model="queryParams.goodsCode" placeholder="请输入产品编码"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form ref="form" :model="form" :rules="rules">
      <div v-if="selectedRows.length > 0">
        <span>已勾选数量合计: {{ selectedRows.reduce((acc, row) => acc + row.orderCount, 0) }}</span>
      </div>
      <el-table show-summary :summary-method="totalOutYear" :data="columns" ref="dragTable" row-key="id" v-loading="loading" @sort-change="handleSortChange" @selection-change="handleSelectionChange" :max-height="maxHeight">
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" label="序号" type="index" width="50">
          <template slot-scope="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip/>
        <el-table-column sortable label="产品编码" align="center" prop="goodsCode" />
        <el-table-column sortable label="产品名称" align="center" prop="goodsName"  show-overflow-tooltip/>
        <el-table-column sortable label="产品型号" align="center" prop="goodModel" />
        <el-table-column sortable label="产品状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.goods_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="订单单价" prop="goodsUnitPrice"/> -->
        <el-table-column sortable label="订单数量" align="center" prop="orderCount" />
        <el-table-column sortable label="客户名称" align="center" prop="order.companyName" show-overflow-tooltip/>
        <el-table-column sortable label="业务员" align="center" prop="order.salesmanName" />
        <el-table-column sortable label="需求日期" align="center" prop="deliveryTime" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable align="center" label="库存总量" prop="stockCount" />
        <el-table-column  align="center" label="可用数量" prop="remainderCount">
          <template slot-scope="scope">
            <el-tag type="success">{{ scope.row.remainderCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="锁定数量" prop="lockCount" width="150">
          <template slot-scope="scope">
            <el-input-number v-if="scope.row.orderCount >= scope.row.remainderCount" size="mini"
              @change="lockCountChange(scope.row)" v-model="scope.row.lockCount" :min="0"
              :max="scope.row.remainderCount"></el-input-number>
            <el-input-number v-if="scope.row.orderCount < scope.row.remainderCount" size="mini"
              @change="lockCountChange(scope.row)" v-model="scope.row.lockCount" :min="0"
              :max="scope.row.orderCount"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="请购数量" prop="pleaseBuyCount" width="150">
          <template slot-scope="scope">
            <el-input-number size="mini" v-model="scope.row.pleaseBuyCount" :min="0"
             @change="pleaseBuyCountChange(scope.row)" :max="scope.row.orderCount"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width" >
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="choseGoods(scope.row)">选用锁定产品</el-button>
            <el-button size="mini" type="text" icon="el-icon-search"
              @click="choseGoodsDeatil(scope.row)">锁定产品明细</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="dialog-footer" slot="footer">
      <el-button type="primary" @click="submitBuyForm" v-if="this.queryParams.status==1">发起请购到生产部</el-button>
      <el-button type="primary" @click="submitBuyToCaigouForm" v-if="this.queryParams.status==1">发起请购到采购部</el-button>
      <el-popconfirm :title="`确认要把锁定数量一键清零吗？`" @confirm="oneKeyReset()" style="margin-left: 10px;margin-right: 10px;">
        <el-button slot="reference" type="danger" icon="el-icon-s-open">一键清零</el-button>
      </el-popconfirm>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <choseGoods-form-list @ok="getList" ref="choseGoodsFormList"></choseGoods-form-list>
    <choseGoodsDeatil-form-list ref="choseGoodsDeatilFormList" @ok="getList"></choseGoodsDeatil-form-list>
  </el-dialog>
</template>

<script>
import {addAction, isEmpty, deleteAction, getAction, getById, accAdd} from '@/api/manage'
import ChoseGoodsFormList from '@/views/develop/goodsSaleMaterial/module/ChoseGoodsFormList'
import ChoseGoodsDeatilFormList from '@/views/develop/goodsSaleMaterial/module/ChoseGoodsDeatilFormList'

export default {
  name: "PleaseBuyFormGoodsNew",
  dicts: ['goods_status', 'isdo'],
  components: {
    ChoseGoodsFormList,
    ChoseGoodsDeatilFormList
  },
  data() {
    return {
      maxHeight: (window.innerHeight * 0.9 - 260) ,
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "订单产品请购",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      proId: "",
      status: "",
      columns: [],
      total: 0,
      // 表单校验
      rules: {
      },
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        id: null,
        name: null,
        taxNo: null,
        addr: null,
        tel: null,
        bankName: null,
        bankNo: null,
        info: null,
        status: "1",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        projectId: null,
        type: null,
      },
      url: {
        list: '/goodsSale/goodsSale/listByProOrder',
        pleaseBuyForPrjNew: '/goodsSaledo/goodsSaledo/pleaseBuyForPrjNew',
        pleaseBuyForPrjNewToCaigou: '/goodsSaledo/goodsSaledo/pleaseBuyForPrjNewToCaigou',
      },
      selectedRows: [], // 用于存储勾选的行数据
    };
  },
  updated() {
    this.$nextTick(() => {
    // tab 绑定ref 属性
      // this.$refs["dragTable"].doLayout();
    });
  },
  created() {

  },
  methods: {
    totalOutYear(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1 || index === 2 || index === 3  || index === 4 || index === 5  || index === 6 || index === 8  || index === 9  || index === 10 || index === 11  || index === 12  || index === 13  || index === 18  || index === 19 || index === 20) {
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property != 'implementYear') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];
        }
      });
      return sums
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
     /** 搜索按钮操作 */
     handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    choseGoodsDeatil(row) {
      this.$refs.choseGoodsDeatilFormList.show(row,"1");
    },
    choseGoods(row) {
      this.$refs.choseGoodsFormList.showRukuGoods(row);
    },
    getList() {
      this.loading = true;
      getAction(this.url.list, this.queryParams).then(response => {
        this.columns = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        name: null,
        master: null,
        customId: null,
        customName: null,
        companyName: null,
        contractDate: null,
        contractMoney: null,
        auditMoney: null,
        checkDate: null,
        checkState: null,
        fundCallback: null,
        infomation: null,
        shengyu: null,
      };
      this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      //this.proId = row.id;
      this.queryParams.status = row.status;
      this.queryParams.projectId = row.id;
      this.queryParams.sortByColumn = "sort";
      this.queryParams.isAsc = "asc";
      this.open = true;
      this.getList();
    },
    /** 提交按钮 */
    submitBuyForm() {
      let that = this;

      let arrays = that.columns;
      let count = 0;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].pleaseBuyCount === 0) {
          count++;
        }

        if (isEmpty(arrays[i].pleaseBuyCount)) {
          this.$message({ message: '第'+(i+1)+'行数据，请购数量不能为空。', type: 'warning' });
          return;
        }

        if (isEmpty(arrays[i].lockCount)) {
          this.$message({ message: '第'+(i+1)+'行数据，锁定数量不能为空。', type: 'warning' });
          return;
        }
        console.log(arrays[i].pleaseBuyCount,'arrays[i].pleaseBuyCount');
        console.log(arrays[i].lockCount,'arrays[i].lockCount');
        console.log(arrays[i].orderCount,'arrays[i].orderCount');

        if (arrays[i].pleaseBuyCount + arrays[i].lockCount != arrays[i].orderCount) {
          this.$message({ message: '第'+(i+1)+'行数据，请购数量+锁定数量不等于订单数量。', type: 'warning' });
          return;
        }






      }
      if(count===arrays.length){
        this.$message({
          message: '请购数量都为0，无需请购。',
          type: 'warning'
        });
        return;
      }

      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsOrderIn = Object.assign({});
          goodsOrderIn.projectId = this.queryParams.projectId;
          goodsOrderIn.proStatus = this.queryParams.status;
          goodsOrderIn.columns = that._data.columns;
          addAction(this.url.pleaseBuyForPrjNew, goodsOrderIn).then(response => {
            this.$modal.msgSuccess("请购成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },

    submitBuyToCaigouForm() {
      let that = this;
      let arrays = that.columns;
      let count = 0;
      for (let i = 0; i < arrays.length; i++) {
        if (arrays[i].pleaseBuyCount === 0) {
          count++;
        }
        if (isEmpty(arrays[i].pleaseBuyCount)) {
          this.$message({ message: '第'+(i+1)+'行数据，请购数量不能为空。', type: 'warning' });
          return;
        }
        if (isEmpty(arrays[i].lockCount)) {
          this.$message({ message: '第'+(i+1)+'行数据，锁定数量不能为空。', type: 'warning' });
          return;
        }
         console.log(arrays[i].pleaseBuyCount,'arrays[i].pleaseBuyCount');
        console.log(arrays[i].lockCount,'arrays[i].lockCount');
        console.log(arrays[i].orderCount,'arrays[i].orderCount');

        if (arrays[i].pleaseBuyCount + arrays[i].lockCount != arrays[i].orderCount) {
          this.$message({ message: '第'+(i+1)+'行数据，请购数量+锁定数量不等于订单数量。', type: 'warning' });
          return;
        }

      }
      that.$refs["form"].validate(valid => {
        if (valid) {
          const goodsOrderIn = Object.assign({});
          goodsOrderIn.projectId = this.queryParams.projectId;
          goodsOrderIn.proStatus = this.queryParams.status;
          goodsOrderIn.columns = that._data.columns;
          addAction(this.url.pleaseBuyForPrjNewToCaigou, goodsOrderIn).then(response => {
            this.$modal.msgSuccess("请购成功");
            this.open = false;
            this.$emit('ok');
          });
        }
      });
    },

    lockCountChange(row) {
      row.pleaseBuyCount = row.orderCount - row.lockCount;
    },

    pleaseBuyCountChange(row){
      row.lockCount = row.orderCount - row.pleaseBuyCount;
    },

    oneKeyReset() {
      this.columns.forEach((item, index) => {
        this.columns[index].lockCount = 0;
        this.columns[index].pleaseBuyCount = this.columns[index].orderCount;
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
  },
};
</script>
<style></style>
